package com.atcjx.service;

import com.atcjx.MyUtils.IdUtils;
import com.atcjx.mapper.ArticleMapper;
import com.atcjx.mapper.TagMapper;
import com.atcjx.pojo.Article.Article;
import com.atcjx.pojo.Article.ArticleDTO;
import com.atcjx.pojo.Article.ArticleVO;
import com.atcjx.pojo.Query.Article.ArticleQueryDTO;
import com.atcjx.pojo.Query.Article.ArticleQueryPo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author admin
 * @version 1.0.0
 * @ClassName ArticleServiceImpl.java
 * @Description TODO
 * @createTime 2021年09月20日 15:41:00
 */
@Service
public class ArticleServiceImpl  {
    @Autowired
    ArticleMapper articleMapper;

    @Autowired
    TagMapper tagMapper;
    public PageInfo<ArticleVO> getArticles(ArticleQueryDTO articleQueryDTO,int page,int limit) {
        ArticleQueryPo articleQueryPo = articleQueryDTO.toArticleQueryPo();
        PageHelper.startPage(page,limit);
        List<Article> articles = articleMapper.getArticlesByCondition(articleQueryPo);
        PageInfo pageInfo=new PageInfo(articles);
        ArrayList<ArticleVO> articleVOS = Lists.newArrayList();
        for (Article article : articles) {
            articleVOS.add(ArticleVO.fromArticlePO(article));
        }
        pageInfo.setList(articleVOS);
        return pageInfo;
    }


    public String insArticle(ArticleDTO articleDTO) {
        Article article=articleDTO.toArticlePo(false);
        String id= IdUtils.getRandomStringId();
        article.setId(id);
        articleMapper.insert(article);
        tagMapper.deleteTagArticleMapping(article.getId());
        for(String tags:article.getArtTags()){
            String articleId=article.getId();
            tagMapper.addArticleMapping(articleId,tags);
        }
        return id;
    }


    public void deleteById(String id) {
        articleMapper.deleteArticle(id);
    }

    public void updateArticle(ArticleDTO articleDTO, String id) {
        Article article = articleDTO.toArticlePo(true);
        article.setId(id);
        articleMapper.updateById(article);
        tagMapper.deleteTagArticleMapping(id);
        for(String tags:article.getArtTags()){
            tagMapper.addArticleMapping(id,tags);
        }
    }

}
